package com.shop.admin.controller;


import com.shop.web.exception.GCRuntimeException;
import com.shop.web.exception.NeedLoginException;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class AdminControllerAdvice {

    @ExceptionHandler(BindException.class)
    public BaseResponse bindException(BindException e) {
        return BaseResponse.ERROR_PARAM.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse bindException(MethodArgumentNotValidException e) {
        return BaseResponse.ERROR_PARAM.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(NeedLoginException.class)
    public BaseResponse needLoginException(NeedLoginException e) {
        return BaseResponse.NEED_LOGIN;
    }

    @ExceptionHandler(GCRuntimeException.class)
    public BaseResponse gcRuntimeException(HttpServletRequest httpServletRequest, GCRuntimeException e) {
        String reuestURI = httpServletRequest.getRequestURI();
        log.error("统一拦截业务异常 gcRuntimeException(). requestURI -> " + reuestURI);
        return new BaseResponse(e.getcode(), e.getmsg(), "");
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse systemExption(HttpServletRequest httpServletRequest, Exception e) {
        String reuestURI = httpServletRequest.getRequestURI();
        log.error("统一拦截异常 systemExption(). requestURI -> " + reuestURI, e);
        return BaseResponse.SYSTEM_EXCEPTION;
    }


}
